require "Net/send_Msg"
require 'View/UIBase/UIBase'
require 'View/BattleUI/TeamPartnerInfo'

UIGuildBossBattleTeam = UIBase.New(PanelNames.UIGuildBossBattleTeam);
local allRoleNum = 10;--上阵人数总数
local allFormationNum = 2;
local TeamType = {
    Main = 1,
    Help = 2,
}
function UIGuildBossBattleTeam.Init(data)
    UIBase.Init(UIGuildBossBattleTeam);
    BattlePlaybackManager.SetFightType(EnumConst.FightTypeConst.GuildBoss)

end

--定义控件
function UIGuildBossBattleTeam:OnCreate()
    self.fightType = EnumConst.FightTypeConst.GuildBoss;
    --table
    self.roles = {};--布阵角色组件
    self.roleIndex = {};--角色索引
    self.rects = {};--角色碰撞方块
    self.roleBottoms = {};--角色品质框
    self.teamIndexBtns = {};--队伍索引按钮
    ---@param tabHeroItem table<string,FairyGUI.GComponent>
    self.tabHeroItem = {};--根据英雄唯一id存储他的组件
    self.isClickHero = true;--是否可以对英雄操作

    self:initData()
    --list
    self.dynamicList = self:GetChild("headList")
    --controller
    self.teamTypeCtrl = self:GetController("team");--职业类型切换
    --text
    self.linkLevelText = self:GetChild("Text_wisdomlevel");
    self.tipText = self:GetChild("Text_SubstituteTips");
    self.tipText.text = getLanguage("GuildInvestment_1129");
    self.titleText = self:GetChild("Text_title");
    self.titleText.text = getLanguage("FunctionName1120");
    --btn
    self.backBtn = self:GetChild("BtnBack");--返回
    self.resetHeroBtn = self:GetChild("n50");--重置上阵英雄
    self.btnBoss = self:GetChild("BtnBoss");--开战！
    self.btnTips = self:GetChild("help");--提示

    for i = 1, allFormationNum do
        local teamIndexBtn = self:GetChild("team" .. i);--队伍索引
        table.insert(self.teamIndexBtns, teamIndexBtn);
    end

    --group
    self.draggableBox = self:GetChild("draggableBox");--人物可滑动范围

    --component
    --self.titleNode = self:GetChild("teamTitleNode");--所有角色头顶信息总节点 （为了解决自动合批会导致层级疯狂变化的处理方式，不将头顶信息与角色分开会导致某些情况下层级显示错误）
    --添加组件
    for i = 1, allRoleNum do
        --添加角色底框
        local bottom = self:GetChild("Loader_Left" .. i);
        table.insert(self.roleBottoms, bottom);
        --添加角色碰撞框
        local rect = self:GetChild("leftRect" .. i)
        table.insert(self.rects, rect);
        --添加角色组件
        local role = self:GetChild("left" .. i);
        role.displayObject.gameObject.name = "left" .. i;
        role.draggable = true;
        role.onTouchBegin:Add(function()
            if not self.isClickHero then
                return;
            end
            self.isMove = true;
            self:onDragStartFunc(role)
        end);
        role.onTouchMove:Add(function()
            if not self.isClickHero then
                return;
            end
            self:onDragMoveFunc(role)
        end);
        role.onTouchEnd:Add(function()
            if not self.isClickHero then
                return;
            end
            self:onDragEndFunc(role)
            self.isMove = false;
        end);
        table.insert(self.roles, role);
        role.onClick:Add(function()
            self:onClickHero(self.tabHeroPosData[i], self.tabHeroItem[self.tabHeroPosData[i].partnerId]);
        end)
        table.insert(self.roleIndex, role.parent:GetChildIndex(role));
    end

    self:addEvent();
end

function UIGuildBossBattleTeam:OnEnable()
    self.linkLevelText.text = string.format(getLanguage("GuildInvestment_1130"), HeroLinkManager.GetHeroLevel());
    self:LocalListenEvent();
    self:initData();
    self.tableHeroes = logicMgr.GuildManager.getGuideBossHeroes()
    self.isClickBattle = false;
    self:initSaveFormation()
    --GuildManager.setGuideBossHeroes(data)
    self:refresh();
end

function UIGuildBossBattleTeam:OnDisable()
    self:LocalCloseEvent()
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    ctrlItem.onClear();

end

function UIGuildBossBattleTeam:OnDestroy()

    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    ctrlItem.onClear();
    ctrlItem.Destroy();
    self:removeEvent();
end

--拖动开始
function UIGuildBossBattleTeam:onDragStartFunc(item)
    if item.draggable then
        AudioManager.Play(1031)
        --item.parent:SetChildIndex(item, item.parent:GetChildIndex(self.titleNode) - 1);
        local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
        local type = self.isShowTitle and 1 or 0;
        ctrlItem.updateTitle(item:GetChild("title"), item.data, type, item.data.teamIdx);

        --item:GetChild("title").visible = true;
        --local titleItem = logicMgr.UIShowManager.getTeamHeroItem(item.data.teamIndex, item.data.teamIdx)
        --titleItem.visible = false;
        --item.parent:SetChildIndex(logicMgr.UIShowManager.getTeamHeroItem(item.data.teamIndex,item.data.teamIdx),999);
    end
end
--拖动途中
function UIGuildBossBattleTeam:onDragMoveFunc(item)
    if self.isMove == false then
        return ;
    end
    local index = 0;
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    --ctrlItem.updateTitlePos(item, item.data, item.data.teamIdx);
    for i = 1, #self.roles do
        if self.roles[i] == item then
            index = i;
            break ;
        end
    end
    local inPos = 0;
    for i = 1, #self.rects do
        if isIntersect(self.rects[i], item) == true then
            inPos = i;
            break
        end
    end

    for i = 1, #self.rects do
        if (index ~= i) then
            self.roles[i]:SetPosition(self.rects[i].x, self.rects[i].y, 0);
            ctrlItem.updateTitlePos(self.roles[i], self.roles[i].data, self.roles[i].data.teamIdx);

        end
    end
    if (inPos ~= 0) then
        if (inPos ~= index) then
            self.roles[inPos]:SetPosition(self.rects[index].x, self.rects[index].y, 0);
            ctrlItem.updateTitlePos(self.roles[inPos], self.roles[inPos].data, self.roles[inPos].data.teamIdx);
        end
    end

end
--拖动结束
function UIGuildBossBattleTeam:onDragEndFunc(item)
    if self.isMove == true then
        self.isMove = false;
    end
    AudioManager.Play(1032)

    local index = 0;
    for i = 1, #self.roles do
        if self.roles[i] == item then
            index = i;
            break ;
        end
    end
    local inPos = 0;
    for i = 1, #self.rects do
        if isIntersect(self.rects[i], item) == true then
            inPos = i;
            break
        end
    end
    if (inPos ~= 0) then
        self:changePosByIndex(index, inPos);
        --else
    end
    item:SetPosition(self.rects[index].x, self.rects[index].y, 0);
    if (index ~= 0) then
        item.parent:SetChildIndex(item, self.roleIndex[index]);
    end
end
--更改位置
function UIGuildBossBattleTeam:changePosByIndex(idx1, idx2)
    local tempIdx;
    if idx2 ~= idx1 then
        tempIdx = self.formations[self.teamIndex][idx1]
        self.formations[self.teamIndex][idx1] = self.formations[self.teamIndex][idx2];
        self.formations[self.teamIndex][idx2] = tempIdx;
    end
    self:initFormation();
    self:rendererFormation();
end

function UIGuildBossBattleTeam:addEvent()
    --btnChangeFormation.onClick:Add(function()
    --    self.ShowSelectFom(1);
    --end);
    self.teamTypeCtrl.onChanged:Add(function()
        self:onClickType()
    end);
    self:RegisterOnClick(self.btnBoss, self.onClickBattle);
    self:RegisterOnClick(self.resetHeroBtn, self.onResetHero);
    self:RegisterOnClick(self.backBtn, self.onCloseClick);
    self:RegisterOnClick(self.btnTips, self.onClickTip);
    for i = 1, #self.teamIndexBtns do
        self:RegisterOnClick(self.teamIndexBtns[i], function()
            self:onChangedFormation(i)
        end)
    end

end

function UIGuildBossBattleTeam:removeEvent()
    self.teamTypeCtrl.onChanged:Clear();
end

function UIGuildBossBattleTeam:LocalListenEvent()

end

function UIGuildBossBattleTeam:LocalCloseEvent()

end

--初始化
function UIGuildBossBattleTeam:initData()
    ---@param tabHeroPosData table<table<BattleTeamPartnerInfo>>
    self.tabHeroPosData = {};--上阵的角色信息

    ---@param formations table<table<string>>
    self.formations = {};--当前阵容 key1:主队，2替补队
    for i = 1, allFormationNum do
        self.formations[i] = {};
    end
    ---@param tableHeroes table<BattleTeamPartnerInfo>
    self.tableHeroes = {};--可使用的所有英雄

    ---@param showHeroes table<BattleTeamPartnerInfo>
    self.showHeroes = {};--可选择的所有英雄

    self.teamIndex = 1;--1为主队 2为替补队

    self.curTabType = 0; --选择的英雄职业
end

--初始化保存的上阵队伍
function UIGuildBossBattleTeam:initSaveFormation()
    local formation = logicMgr.GuildManager.getGuideBossInfo().formation;
    for i = 1, 2 do
        self.formations[i] = formation[i]
        local battleState = i == 1 and EnumConst.GuildStateType.Battle or EnumConst.GuildStateType.HelpBattle;
        for k, v in pairs(self.formations[i]) do
            logicMgr.GuildManager.setHeroState(v, battleState);
        end
    end
end

----初始化阵容数据
function UIGuildBossBattleTeam:initFormation()
    --根据self.formations数据排位显示
    local tempFormation = self.formations[self.teamIndex];
    local num = allRoleNum;

    for i = 1, num do
        local partnerId = tempFormation[i];
        if self.tabHeroPosData[i] == nil then
            self.tabHeroPosData[i] = BattleTeamPartnerInfo.New(1)
        end
        if partnerId and tonumber(partnerId) ~= 0 then
            self.tabHeroPosData[i]:setInfo(GuildManager.getGuideBossHeroById(partnerId));
            --for k = 1, #self.tableHeroes do
            --    if tostring(partnerId) == tostring(self.tableHeroes[k].partnerId) then
            --        break ;
            --    end
            --end
        else
            self.tabHeroPosData[i]:reset(1);
        end
    end
end
--初始化阵容表现
function UIGuildBossBattleTeam:rendererFormation()
    for i = 1, #self.tabHeroPosData do
        if #self.roles >= i then
            local role = self.roles[i];
            local pos = self.rects[i];
            if role.dragBounds == nil or role.dragBounds.y ~= self.draggableBox.y then
                role.dragBounds = UnityEngine.Rect.New(self.draggableBox.x, self.draggableBox.y, self.draggableBox.actualWidth, self.draggableBox.actualHeight);
            end
            role.draggable = true;
            role.visible = true;
            role:SetPosition(pos.x, pos.y, 0);

            local itemData = self.tabHeroPosData[i];
            if itemData.partnerId ~= nil then
                self.roleBottoms[i].visible = true;
                local bIndex = Config.IconQualityBottom[logicMgr.HeroManager.starToQuality(itemData.star)];

                self.roleBottoms[i].url = "ui://ICONAtlas/" .. bIndex;
            else
                self.roleBottoms[i].visible = false;
            end
            --role:GetController("type").selectedIndex =

            local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
            local type = self.isShowTitle and 1 or 0;
            --table.insert(self.teamHeroItemList, ctrlItem)
            if ctrlItem ~= nil then
                ctrlItem.initData(role, itemData, i, type, function(data)
                    --UIGuildBossBattleTeam:showHeroEffect(data)
                end, self.fightType);
            end
            if self.tabHeroPosData[i].partnerId == nil then
                role.draggable = false;
            else
                role.draggable = true;
            end
        end
    end
end

function UIGuildBossBattleTeam:setData(index, itemobj)
    index = index + 1
    local itemValue = self.showHeroes[index];
    local go = itemobj:GetChild("hero");
    local type = self.isShowTitle and 1 or 0;
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    local typeCtrl = itemobj:GetController("type")
    typeCtrl.selectedIndex = itemValue.masterName and 1 or 0;

    if charactor ~= nil then
        --初始英雄信息
        if itemValue then
            charactor.initData(go, itemValue, nil, self.fightType);
            charactor.updateState(itemobj, itemValue, true);

        end
    end
    local isTouch
    if (not itemValue.playerId) or tostring(itemValue.playerId) == logicMgr.HeroManager.GetRoleId() then
        isTouch = true
    end
    go.onTouchBegin:Clear()
    go.onTouchEnd:Clear()
    if typeCtrl.selectedIndex == 1 then
        local timerId
        go.onTouchBegin:Add(function(evt)
            isTouch = true
            timerId = utimer.timeCall(function()
                showUI(PanelNames.UIOtherHeroInfo, tostring(itemValue.playerId), itemValue.partnerId)
                utimer.remove(timerId)
                timerId = nil
                isTouch = false
            end, 500, 1);
        end)
        go.onTouchEnd:Add(function(evt)
            if timerId then
                utimer.remove(timerId)
                timerId = nil
            end
        end)
    else
        isTouch = true
    end
    go.onClick:Clear();
    go.onClick:Add(function(evt)
        if isTouch then
            self:onClickHero(itemValue, go);
        end
    end)
    go.displayObject.gameObject.name = "card" .. index;
    if itemValue then
        self.tabHeroItem[itemValue["partnerId"]] = itemobj;
    end
end

function UIGuildBossBattleTeam:refresh()

    self:onClickType()

    self:initFormation();
    self:rendererFormation();
    if self.isInit then
        self.isInit = false;
    end
end
----检查是否可以显示
--function UIGuildBossBattleTeam:checkShow(isShow,hero)
--
--end

-------------------------------按钮监听
---关闭页面
function UIGuildBossBattleTeam:onCloseClick()
    closeUI(PanelNames.UIGuildBossBattleTeam);
end
--点击英雄头像或小人之后
function UIGuildBossBattleTeam:onClickHero(heroData, go)
    if not self.isClickHero then
        return;
    end
    local data = clone(heroData);
    local hero = GuildManager.getGuideBossHeroById(data.partnerId);
    if hero ~= nil then
        if hero.state == EnumConst.GuildStateType.UnBattle then
            --已上阵同名英雄
            UISysTips.AddMsg(getLanguage("GuildInvestment_1138"));

            return ;
        end

        if hero.state == EnumConst.GuildStateType.Battle or hero.state == EnumConst.GuildStateType.HelpBattle then
            --下阵
            for i = 1, #self.tabHeroPosData do
                if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i].partnerId == data.partnerId then
                    logicMgr.GuildManager.setHeroState(data.partnerId, EnumConst.GuildStateType.Normal)
                    self.formations[self.teamIndex][i] = "0";
                    break ;
                end
            end

        elseif hero.state == EnumConst.GuildStateType.Normal then
            --上阵
            local bFull = true;
            local idx = 0;
            for i = 1, allRoleNum do
                if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i].partnerId == nil then
                    --还有可上阵空位
                    bFull = false;
                    idx = i
                    break
                end
            end
            if bFull then
                UISysTips.AddMsg(getLanguage("Character_Tips1"));
                return ;
            else
                local battleState = EnumConst.GuildStateType.Battle;
                if self.teamIndex == TeamType.Help then
                    battleState = EnumConst.GuildStateType.HelpBattle;
                end
                logicMgr.GuildManager.setHeroState(data.partnerId, battleState);
                self.formations[self.teamIndex][idx] = heroData.partnerId;
            end
        end
        local allNameHero = GuildManager.getAllNameHeroByModelId(data.partnerModelId)
        for i = 1, #allNameHero do
            local nameHeroData = allNameHero[i];
            local obj = self.tabHeroItem[nameHeroData.partnerId]
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
            if hero ~= nil then
                if ctrlItem ~= nil then
                    ctrlItem.updateState(obj, nameHeroData, true);
                end
            end
        end
        self:initFormation();
        self:rendererFormation();
        if self.teamIndex == 1 and self:getFormationNum(self.formations[1]) == 10 then
            --主队上满 切换到替补队
            self.isClickHero = false
            utimer.delayCall(function()
                self.isClickHero = true;
                self:GetController("NumTeams").selectedIndex = 1;
                self:onChangedFormation(2);
            end, 500)
        end
    end
end
--传入formation获得上阵人数总数
function UIGuildBossBattleTeam:getFormationNum(formation)
    local count = 0;
    for k, v in pairs(formation) do
        if tonumber(v) ~= 0 then
            count = count + 1;
        end
    end
    return count;
end
--提示
function UIGuildBossBattleTeam:onClickTip()
    local txts = {};
    txts["title"] = "GuildInvestment_1126";
    txts["des"] = "GuildInvestment_1127";
    showUI(PanelNames.CommonTips, txts);
end




--切换英雄职业类型
function UIGuildBossBattleTeam:onClickType(isRest)
    self.curTabType = self:GetController("team").selectedIndex;

    for k, v in pairs(self.tabHeroItem) do
        v.onClick:Clear();
    end

    self.showHeroes = {};
    for i = 1, #self.tableHeroes do
        local hero = self.tableHeroes[i];
        if hero.masterName == nil or logicMgr.HeroManager.isOpenHeroAtlas(hero.partnerModelId) then
            local isShow = 0;
            if self.curTabType == 0 then
                isShow = isShow + 1;
            elseif hero.type == self.curTabType then
                isShow = isShow + 1;
            end
            if self.teamIndex == TeamType.Main then
                if hero.state ~= EnumConst.GuildStateType.HelpBattle then
                    isShow = isShow + 1;
                end
            else
                if hero.state ~= EnumConst.GuildStateType.Battle then
                    isShow = isShow + 1;
                end
            end
            if isShow >= 2 then
                --满足显示条件
                if isRest then
                    hero.state = EnumConst.GuildStateType.Normal;
                end
                table.insert(self.showHeroes, hero);
            end
        end
    end

    table.sort(self.showHeroes, function(a, b)
        local powerA = tonumber(tostring(a.power))
        local powerB = tonumber(tostring(b.power))
        if powerA == powerB then
            return HeroManager.sortHero(a, b);
        elseif powerA == nil or powerB == nil then
            if (powerA == nil) then
                return false
            else
                return true
            end
        elseif powerA > powerB then
            return true
        else
            return false
        end
    end);
    self.index = 0;
    self.dynamicList.itemRenderer = function(index, obj)
        self:setData(index, obj);
    end
    self.dynamicList.numItems = #self.showHeroes;
    self.dynamicList.lineGap = 5

end
--切换队伍
function UIGuildBossBattleTeam:onChangedFormation(type)
    self.teamIndex = type;
    self:onClickType();
    self:initFormation();
    self:rendererFormation();
end

function UIGuildBossBattleTeam:onResetHero()
    --self.formations[self.teamIndex] = {};
    for i = 1, #self.tabHeroPosData do
        if self.tabHeroPosData[i].partnerId ~= nil then
            local hero = GuildManager.getGuideBossHeroById(self.tabHeroPosData[i].partnerId);
            if hero then
                logicMgr.GuildManager.setHeroState(self.tabHeroPosData[i].partnerId, EnumConst.GuildStateType.Normal)
            end
        end
    end
    self.formations[self.teamIndex] = {};
    self:onClickType();
    self:initFormation();
    self:rendererFormation();
end
--点击开战
function UIGuildBossBattleTeam:onClickBattle()
    local isMain = false;
    local isHelp = false;
    for k = 1, #self.formations[1] do
        if tonumber(tostring(self.formations[1][k])) ~= 0 and tonumber(tostring(self.formations[1][k])) ~= nil then
            isMain = true;
        end
    end
    for k = 1, #self.formations[2] do
        if tonumber(tostring(self.formations[2][k])) ~= 0 and tonumber(tostring(self.formations[2][k])) ~= nil then
            isHelp = true;
        end
    end
    if not isMain then
        UISysTips.AddMsg(getLanguage("GuildBossTip2"));
        self.isClickBattle = false;
        return ;
    elseif not isHelp then
        UISysTips.AddMsg(getLanguage("GuildBossTip1"));
        self.isClickBattle = false;
        return ;
    end

    local isGo = true
    if UIGuildBossBattleTeam:getFormationNum(self.formations[1]) < allRoleNum or UIGuildBossBattleTeam:getFormationNum(self.formations[2]) < allRoleNum then
        for k, v in pairs(self.showHeroes) do
            if v.state == EnumConst.GuildStateType.Normal then
                --弹提示
                isGo = false;
            end
        end
    end
    if isGo then
        UIWaiting.WaitingShow(true);
        self:gotoBattle()
    else
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
        pop.Init("53", function(b)
            if b then
                UIWaiting.WaitingShow(true);
                UIGuildBossBattleTeam:gotoBattle()
                self.isClickBattle = false;
            end
        end);
    end
end

function UIGuildBossBattleTeam:gotoBattle()
    if self.isClickBattle then
        return ;
    end
    FightManager.SetMyTeam(self.tabHeroPosData)
    if self.formations then
        local battleGFormation = {}

        for i = 1, #self.formations do
            for k = 1, #self.formations[i] do
                if i == 1 then
                    battleGFormation[k] = self.formations[i][k];
                else
                    battleGFormation[k + allRoleNum] = self.formations[i][k];
                    --替补
                end
            end

        end
        logicMgr.GuildManager.helpManInfos = {};
        for i, v in pairs(self.formations[2]) do
            local data = logicMgr.HeroManager.getHeroDatabyPartnerId(v)
            if data == nil then
                data = GuildManager.getGuideBossHeroById(v)
            end
            if data then
                local info = {};
                info.icon = HeroManager.GetHeroIconByModelId(data.partnerModelId, data.skinId)
                info.partnerModelId = data.partnerModelId;
                info.dead = false;
                table.insert(logicMgr.GuildManager.helpManInfos, data)
            end
        end

        for i = 1, 20 do
            if battleGFormation[i] == nil then
                battleGFormation[i] = "0";
            end
        end
        BattleSceneCacheResouce:CacheBattleFormation(self.formations, {})
        --请求boss战斗
        local bossId = logicMgr.GuildManager.getGuideBossConfig().f_HeroID;
        local unionId = logicMgr.GuildManager.getUnionId();
        local param = {};
        param.unionId = unionId;
        param.bossId = bossId;
        param.formation = battleGFormation;
        param.allianceId = logicMgr.GuildManager.getAllianceId();
        unionHandler.reqUnionBossBattle(param)
        self.isClickBattle = true;
    end
end

return UIGuildBossBattleTeam;